﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SYSoft.Comm;
using SYSoft.Model;
using SYSoft.Model.Model.Models;
using SYSoft.Model.Models.SystemManage;
using SYSoft.Model.ViewModels.SystemManage;
using SYSoft.Repository;
using SYSoft.Services.SystemManage;

namespace SYSoft.Controllers.SystemManage
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public class UserController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        readonly ISysUserInfoServices _sysUserInfoServices;
        readonly IUserRoleServices _userRoleServices;
        readonly IRoleServices _roleServices;

        public UserController(IUnitOfWork unitOfWork, ISysUserInfoServices sysUserInfoServices, IUserRoleServices userRoleServices, IRoleServices roleServices)
        {
            _unitOfWork = unitOfWork;
            _sysUserInfoServices = sysUserInfoServices;
            _userRoleServices = userRoleServices;
            _roleServices = roleServices;
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<PageModel<sys_User>>> GetAllUsers(int pageIndex = 1, int pageSize = 50)
        {
            var userList = await _sysUserInfoServices.QueryPage(null, pageIndex, pageSize, " Id desc ");
            return MessageModel.CreateSuccessResult(userList);
        }

        /// <summary>
        /// 获取所有用户及其角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<PageModel<sys_User>>> GetUserList(int pageIndex = 1, int pageSize = 50)
        {
            // 这里可以封装到多表查询，此处简单处理
            var userList = await _sysUserInfoServices.QueryPage(null,pageIndex,pageSize);
            var allUserRoles = await _userRoleServices.Query();
            var allRoles = await _roleServices.Query();

            
            foreach (var user in userList.data)
            {
                var currentUserRoles = allUserRoles.Where(d => d.UserId == user.Id).Select(d => d.RoleId).ToList();
                user.Roles = allRoles.Where(d => currentUserRoles.Contains(d.Id)).ToList();
            }


            return MessageModel.CreateSuccessResult(userList);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<int>> Post([FromBody] sys_User user)
        {
            user.PassWord = MD5Helper.MD5Encrypt32(user.PassWord);
            //sysUserInfo.uRemark = _user.Name;
            int res = await _sysUserInfoServices.Add(user);
            if (res > 0)
                return MessageModel.CreateSuccessResult<int>(res);
            return MessageModel.CreateFailedResult<int>("Id必须大于0");
        }



        /// <summary>
        /// 修改用户状态
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel> changeUserStatus(int userId,int status)
        {
         
            var res = await _sysUserInfoServices.Update($"update t_user set Status={status} where Id={userId}");
            if (res)
                return MessageModel.CreateSuccessResult<string>("sucess");
            return MessageModel.CreateFailedResult<string>("修改用户信息失败！！");
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel<string>> Update([FromBody] sys_User user)
        {
            user.UpdateOn = DateTime.Now;
            //sysUserInfo.UpdateBy = Operator.UserId; //操作者
            var res = await _sysUserInfoServices.Update(user);
            if (res)
                return MessageModel.CreateSuccessResult<string>("sucess");
            return MessageModel.CreateFailedResult<string>("修改用户信息失败！！");
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id)
        {
            if (id > 0)
            {
                var userDetail = await _sysUserInfoServices.QueryById(id);
                bool res = await _sysUserInfoServices.Delete(userDetail);
                if (!res)
                    return MessageModel.CreateFailedResult<string>("删除用户失败！！");
                return MessageModel.CreateSuccessResult("删除用户成功");
            }

            return MessageModel.CreateFailedResult<string>("Id必须大于0");
        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="Id">用户Id</param>
        /// <param name="newpwd">新密码</param>
        /// <param name="oldpwd">旧密码</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel<string>> ChangePwd(int Id,string newpwd,string oldpwd)
        {
            var user =await _sysUserInfoServices.QueryById(Id);
            if(user!=null)
            {
                if(user.PassWord != MD5Helper.MD5Encrypt32(oldpwd)) return MessageModel.CreateFailedResult<string>("旧密码不正确！！");
                user.PassWord = MD5Helper.MD5Encrypt32(newpwd);
                var res =await _sysUserInfoServices.Update(user);
                if(res) return MessageModel.CreateSuccessResult<string>("sucess");
                return MessageModel.CreateFailedResult<string>("修改用户信息失败！！");
            }
            return MessageModel.CreateFailedResult<string>("用户不存在！！");
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>

        [HttpPut]
        public async Task<MessageModel<string>> ResetPwd(int Id, string pwd)
        {
            var user = await _sysUserInfoServices.QueryById(Id);
            if (user != null)
            {
                user.PassWord = MD5Helper.MD5Encrypt32(pwd);
                var res = await _sysUserInfoServices.Update(user);
                if (res) return MessageModel.CreateSuccessResult<string>("sucess");
                return MessageModel.CreateFailedResult<string>("修改用户信息失败！！");
            }
            return MessageModel.CreateFailedResult<string>("用户不存在！！");
        }



        /// <summary>
        /// 根据用户ID获取角色ID集合
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<sys_UserRole>>> GetUserRoles(int userId)
        {
            var model = await _userRoleServices.Query(x => x.Id == userId);
            if(model!=null && model.Count>0)
            {
                return MessageModel.CreateSuccessResult(model);
            }
            return MessageModel.CreateFailedResult<List<sys_UserRole>>("用户不存在！！");
        }
        /// <summary>
        /// 为用户分配角色
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel> assignUserRoles(int userId, int[] roleIds)
        {
            /*需要用事务
             *
             *
             */
            if (roleIds.Length < 1)
                return new MessageModel("为用户分配角色失败！！");
            try
            {
                _unitOfWork.BeginTran();
                // 1. 先删除该用户所有角色
                await _userRoleServices.Delete(d => d.UserId == userId);

                List<sys_UserRole> sys_UserRoles = new List<sys_UserRole>();
                for (int i = 0; i < roleIds.Length; i++)
                {
                    sys_UserRoles.Add(new sys_UserRole { UserId = userId, RoleId = roleIds[i] });
                }
                // 2 。新增用户角色
                var res = await _userRoleServices.Add(sys_UserRoles);

                _unitOfWork.CommitTran();

                if (res > 0)
                    return MessageModel.CreateSuccessResult();
                else
                    return new MessageModel("为用户分配角色失败！！");
            }
            catch (Exception e)
            {
                _unitOfWork.RollbackTran();
                LogHelper.Error( e.Message);
            }

            return new MessageModel("为用户分配角色失败！！");

        }
    }
}